package cn.edu.jlu.community.app.services.express;

import android.app.AlertDialog;
import android.support.v4.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import cn.edu.jlu.community.R;

/**
 * Created by lkk on 3/27/15.
 */
public class ExpressFragment extends Fragment {

    private Resources mResources;
    private String[] mCompany_code_array;
    private String[] mCompany_name_array;
    private String[] mCompany_logo_array;

    private LinearLayout mExpress_post_layout;
    private LinearLayout mExpress_coms_layout;

    private EditText mExpressId;
    private TextView mExpress_coms;
    private CardView mSearch_cv;

    private FragmentManager mFragmentManager;
    private Fragment mResultFragment;

    private int mSelectedId;
    private Handler hd;

    public Toast mToast = null;
    public LoadingDialog dialog = null;

    public static ExpressFragment newInstance() {
        ExpressFragment fragment = new ExpressFragment();
        return fragment;
    }

    public ExpressFragment() {
        // Required empty public constructor

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.express_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mSelectedId = 0;
        hd = getHandler();
        dialog = new LoadingDialog(getActivity().getApplicationContext());

        mResources = getResources();
        mCompany_code_array = mResources.getStringArray(R.array.company_code);
        mCompany_name_array = mResources.getStringArray(R.array.company_name);

        mExpressId = (EditText) getView().findViewById(R.id.expressId);
        mExpress_coms = (TextView) getView().findViewById(R.id.express_coms);

        mExpress_post_layout = (LinearLayout) getView().findViewById(R.id.express_post_layout);
        mExpress_post_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mExpressId.requestFocus();
            }
        });

        mExpress_coms_layout = (LinearLayout) getView().findViewById(R.id.express_coms_layout);
        mExpress_coms_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogBuilder();
            }
        });

        mSearch_cv = (CardView) getView().findViewById(R.id.search_cv);
        mSearch_cv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tips = mResources.getString(R.string.msg_load_ing);
                showLoadingDialog(tips);
                ConnHelper.Search(mCompany_code_array[mSelectedId], mExpressId.getText().toString(), hd);
            }
        });
    }

    private void dialogBuilder() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(mResources.getString(R.string.express_dialog_title));
        builder.setCancelable(true);
        builder.setItems(R.array.company_name, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                mSelectedId = item;
                mExpress_coms.setText(mCompany_name_array[item]);
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private void showResult(String jsonStr) {
        mFragmentManager = getActivity().getSupportFragmentManager();
        mResultFragment = ResultFragment.newInstance(jsonStr);

        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.result_fragment, mResultFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    private void removeResult() {
        mFragmentManager = getFragmentManager();

        if (mResultFragment != null) {
            FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.remove(mResultFragment);
            fragmentTransaction.commit();
        }
    }

    private Handler getHandler() {
        return new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    String res = msg.obj.toString();
                    parse(res);
                }
                if (msg.what == -1) {
                    showToast("error");
                }
                dismissLoadingDialog();
            }
        };
    }

    public void parse(String jsonStr) {
        try {
            JSONObject obj = new JSONObject(jsonStr);
            if (obj.get("message").equals("ok")) {
                showResult(jsonStr);
            } else {
                showToast(obj.getString("message"));
                removeResult();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void showToast(String msg) {

        if (mToast == null) {
            mToast = Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(msg);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    public void showLoadingDialog(String dialogStr) {
        dialog = new LoadingDialog(getActivity(), dialogStr);
        dialog.show();
    }


    public void dismissLoadingDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}